30. Exercise: Synchronizing The Weather

This process is going to be very similar to the one we followed when we created our toy app for this lesson. First, we’re going to create a class that represents the “task” we’re going to perform. Then, we’ll create and register an IntentService that will be able to perform that task. Next, we’ll create a class to handle all of our synchronization. Once that’s done, we can move on to rewiring the app to work with our new synchronization strategy.

Create SunshineSyncTask

  • (1) In order to keep all of our code organized, go ahead and create a class called SunshineSyncTask.
  • (2) Within that class, we’re just going to write one method. This method is going to be the main “task” of Sunshine.
  • (3) Call this method syncWeather, and within it, move the logic that was previously in our AsyncTaskLoader for loading the weather data.
  • (4) If you fetch valid results, delete the old weather data and insert the new data.

Create and Register SunshineSyncIntentService

Next, we’ll need a class to handle backgrounding our syncTask. IntentServices are perfect for one off tasks that need to be handled in the background, so we’ll create one here.

  • (1) Create SunshineSyncIntentService class and set it to extend IntentService.
  • (2) Next, create a constructor that calls super and passes the name of this class as a string.
  • (3) Finally, override onHandleIntent. Within it, we’ll call SunshineSyncTask.syncWeather

Create SunshinesyncUtils

Now that we have a way to sync the weather and a way to handle backgrounding that sync, let’s get everything wired up. For that, we’ll create a class called SunshineSyncUtils.

  • (1) Inside we’ll create a startImmediateSync method that will start the IntentService and force an immediate synchronization when called.

Exercise: Smarter Sunshine Syncing 1

Alright, now it's your turn to create all the synchronization classes and hook them up in this exercise. Follow Sunshine exercise 10.01 - SynchronizingTheWeather

Exercise Code

Exercise: S10.01-Exercise-SynchronizingTheWeather

SOLUTION:
  • Create the SunshineSyncTask, and fill out the syncWeather method
  • Create the SunshineSyncIntentService, and have it call syncWeather
  • Add the sync service to the manifest
  • Create SunshineSyncUtils with the startImmediateSync method
  • Call startImmediateSync from SettingsFragment if the location changes